package com.example;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    /**
     * 1、项目启动就监听配置文件变化
     * 2、发生变化后拿到变化值
     * 3、发送邮件
     */

    @Bean
    ApplicationRunner init(NacosConfigManager nacosConfigManager) {
        // 函数式接口可以替换为箭头函数  函数式接口：只有一个方法的类
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {
                ConfigService configService = nacosConfigManager.getConfigService();
                configService.addListener("service-order.properties", "DEFAULT_GROUP", new Listener() {
                    // Executor：线程池，监听器的监听任务实在线程池中运行的
                    @Override
                    public Executor getExecutor() {
                        return Executors.newFixedThreadPool(4);
                    }
                    // 接收配置信息
                    @Override
                    public void receiveConfigInfo(String s) {
                        System.out.println("变化的配置信息" + s);
                        System.out.println("邮件通知、使用gateway的RouteDefinitionWriter进行动态路由");
                    }
                });
                System.out.println("=============");
            }
        };
    }
}